package io.github.kimmking.gateway.filter.my;

import io.github.kimmking.gateway.filter.HttpResponseFilter;
import io.netty.handler.codec.http.FullHttpResponse;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 *
 */
@Slf4j
public class MyHttpResponseFilterChain implements HttpResponseFilter {

    List<HttpResponseFilter> filterList = new ArrayList<>();

    boolean logEnable = false;

    public MyHttpResponseFilterChain(boolean logEnable) {
        this.logEnable = logEnable;
    }

    public MyHttpResponseFilterChain addFilter(HttpResponseFilter f) {
        filterList.add(f);
        return this;
    }

    @Override
    public void filter(FullHttpResponse response) {
        for (HttpResponseFilter filter : filterList) {
            if (logEnable) {
                log.info("responseFilter: {}", filter.getClass().getName());
            }
            try {
                filter.filter(response);
            } catch (Exception e) {
                log.error("filter occur error, filter:{}", filter.getClass().getName(), e);
            }
        }
    }
}
